package com.xxxx.protal.serveice;

import com.xxxx.protal.dao.GoodsRepository;
import com.xxxx.protal.pojo.Goods;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lwf
 * @title: EsSearchService
 * @projectName shop
 * @description: TODO
 * @date 2021/1/515:24
 */
@Service
public class EsSearchService {
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Cacheable(value = "goodsPage",key="#searchKey+'-'+#pageNum+''+#pageSize")
    public List<Goods> pageSearch(String searchKey,Integer pageNum,Integer pageSize){
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new
                NativeSearchQueryBuilder();
        NativeSearchQuery query = nativeSearchQueryBuilder
         /**
          * 第一个参数：关键词
          * 第二个参数：对应es的字段
          */
                .withQuery(QueryBuilders.multiMatchQuery(searchKey,
                        "goodsName"))
          /**
           * 第一个参数：当前页，0开始
           * 第二个参数：每个条数
           * 第三个参数：排序对象
           * 升序/降序
           * 比较字段
           */
             // .withPageable(PageRequest.of(0,5,Sort.Direction.DESC,"goodsId","marketPrice"))
             // 分页
             .withPageable(PageRequest.of(pageNum, pageSize))
             //
              .withSort(SortBuilders.fieldSort("marketPrice").order(SortOrder.ASC))
             //高亮，默认样式<em></em>（斜体）
             // .withHighlightFields(new HighlightBuilder.Field("goodsName"))
             //高亮，指定样式
              .withHighlightBuilder(new
                        HighlightBuilder().field("goodsName").preTags("<span style='color:red;'>").postTags(" </span>"))
                        .build();
             //返回结果
             List<Goods> result=new ArrayList<>();
        SearchHits<Goods> search = elasticsearchRestTemplate.search(query,
                Goods.class);
        for (SearchHit<Goods> searchHit : search) {
            Goods goods=null;
            String highlightMessage = searchHit.getHighlightField("goodsName").get(0);
            System.out.println("高亮-----------");
            System.out.println(highlightMessage);
            //结果对象
            goods=searchHit.getContent();
            goods.setGoogsNameH1(highlightMessage);
            goods.setGoodsNum((int) search.getTotalHits());
            System.out.println("数据："+goods.getGoodsNum());
            result.add(goods);
        }
       return result;
    }

}
